package com.example.administrator.shihuo.fragments;


import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.shihuo.R;
import com.example.administrator.shihuo.adapters.HomePageAdapter;
import com.example.administrator.shihuo.adapters.HomePagerVPAdapter;
import com.example.administrator.shihuo.modle.BannerBean;
import com.example.administrator.shihuo.modle.ChannelBean;
import com.example.administrator.shihuo.modle.GetListViewHeader;
import com.example.administrator.shihuo.modle.GetMeiRiuiJian;
import com.example.administrator.shihuo.modle.HomePageModle;
import com.example.administrator.shihuo.modle.TopicBean;
import com.example.administrator.shihuo.modle.ZoneBean;
import com.example.administrator.shihuo.netConfig.Config;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class HomePagerFragment extends Fragment implements Handler.Callback, PullToRefreshBase.OnRefreshListener2, View.OnClickListener, ViewPager.OnPageChangeListener, AdapterView.OnItemClickListener {

    private int cachePosition = 0;
    private static final String TAG = HomePagerFragment.class.getSimpleName();
    private PullToRefreshListView refreshListView;
    private ListView listView;
    private ViewPager viewPager;
    private ImageView imageOne, imageTwo, imageThree, imageFour, imageFive, imageSix;
    private TextView titleOne, titleTwo, titleThree, titleFour, titleFive, titleSix;
    private TextView textOne, textTwo, textThree, textFour, textFive, textSix;
    private HorizontalScrollView spical;
    private List<HomePageModle> homeData;
    private List<BannerBean> bannerBeans;
    private List<ChannelBean> channelBeans;
    private List<TopicBean> topicBeans;
    private List<ZoneBean> zoneBeans;
    private Handler handler;
    private LinearLayout linear;
    private List<Fragment> fragments;

    private int num;
    private LinearLayout scrollLinear;
    int page = 1;

    public HomePagerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_pager, container, false);
        Log.e(TAG, "sssssssssssss");

        initView(view);

        initData();
        initHeader();
        setListener();
        return view;
    }


    private void initView(View view) {
        refreshListView = ((PullToRefreshListView) view.findViewById(R.id.homepage_refreshlistview));
        refreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        listView = refreshListView.getRefreshableView();
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.listview_hand, null);
        listView.addHeaderView(inflate);
        //find View:inflate的 布局文件
        viewPager = ((ViewPager) inflate.findViewById(R.id.listview_viewpager));
        //图片加载的
        imageOne = ((ImageView) inflate.findViewById(R.id.listview_Image_one));
        imageTwo = ((ImageView) inflate.findViewById(R.id.listview_Image_two));
        imageThree = ((ImageView) inflate.findViewById(R.id.listview_Image_three));
        imageFour = ((ImageView) inflate.findViewById(R.id.listview_Image_four));
        imageFive = ((ImageView) inflate.findViewById(R.id.listview_Image_five));
        imageSix = ((ImageView) inflate.findViewById(R.id.listview_Image_six));
        //Title加载的
        titleOne = ((TextView) inflate.findViewById(R.id.listview_Title_one));
        titleTwo = ((TextView) inflate.findViewById(R.id.listview_Title_two));
        titleThree = ((TextView) inflate.findViewById(R.id.listview_Title_three));
        titleFour = ((TextView) inflate.findViewById(R.id.listview_Title_four));
        titleFive = ((TextView) inflate.findViewById(R.id.listview_Title_five));
        titleSix = ((TextView) inflate.findViewById(R.id.listview_Title_six));
        //Text加载的
        textOne = ((TextView) inflate.findViewById(R.id.listview_Text_one));
        textTwo = ((TextView) inflate.findViewById(R.id.listview_Text_two));
        textThree = ((TextView) inflate.findViewById(R.id.listview_Text_three));
        textFour = ((TextView) inflate.findViewById(R.id.listview_Text_four));
        textFive = ((TextView) inflate.findViewById(R.id.listview_Text_five));
        textSix = ((TextView) inflate.findViewById(R.id.listview_Text_six));
        //专题加载View
        spical = ((HorizontalScrollView) inflate.findViewById(R.id.listview_special));
        scrollLinear = ((LinearLayout) inflate.findViewById(R.id.scroll_linear));
        linear = ((LinearLayout) inflate.findViewById(R.id.listview_linear));
    }

    private void initData() {
        Log.e(TAG, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"+Config.GET_EVERYDAY_PATH + page + Config.PATH_EV);
        handler = new Handler(this);


        OkHttpUtils.get().url(Config.GET_EVERYDAY_PATH + page + Config.PATH_EV).tag("get").build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                Toast.makeText(getContext(), "下载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {
                Message msg = new Message();
                msg.what = 1;
                msg.obj = response;
                handler.sendMessage(msg);

            }
        });


    }

    private void initHeader() {
//          OkHttpUtils.get().url(Config.GET_EVERYDAY_RECOMMEND).tag("get").build().execute(new StringCallback() {

        OkHttpUtils.get().url(Config.GET_LISTVIEW_HEADER).tag("get").build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                Toast.makeText(getContext(), "下载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {

                Message msg = new Message();
                msg.what = 2;
                msg.obj = response;
                handler.sendMessage(msg);
            }
        });

    }

    private void setData() {
        fragments = new ArrayList<>();
        //加载运动 篮球...
        for (int i = 0; i < zoneBeans.size(); i++) {
            String title = zoneBeans.get(i).getTitle();
            String sub_title = zoneBeans.get(i).getSub_title();
            String img_url = zoneBeans.get(i).getImg_url();
            if (i == 0) {
                textOne.setText(sub_title);
                titleOne.setText(title);
                toGetImage(img_url, imageOne);
            }
            if (i == 1) {
                textTwo.setText(sub_title);
                titleTwo.setText(title);
                toGetImage(img_url, imageTwo);
            }
            if (i == 2) {
                textThree.setText(sub_title);
                titleThree.setText(title);
                toGetImage(img_url, imageThree);
            }
        }
        //加载 今日优惠
        for (int i = 0; i < channelBeans.size(); i++) {
            String title = channelBeans.get(i).getTitle();
            String sub_title = channelBeans.get(i).getSub_title();
            String img_url = channelBeans.get(i).getImg_url();

            if (i == 0) {
                textFour.setText(sub_title);
                titleFour.setText(title);
                toGetImage(img_url, imageFour);
            }
            if (i == 1) {
                textFive.setText(sub_title);
                titleFive.setText(title);
                toGetImage(img_url, imageFive);
            }
            if (i == 2) {
                textSix.setText(sub_title);
                titleSix.setText(title);
                toGetImage(img_url, imageSix);
            }
        }
        //加载ViewPager
        for (int i = 0; i < bannerBeans.size(); i++) {
            // 用代码实例化一个ImageView
            ImageView imageView = new ImageView(getContext());
            // 第一个位置设置为选中的icon
            if (i == 0) {
                imageView.setImageResource(R.drawable.truesss);
            } else {
                imageView.setImageResource(R.drawable.falsess);
            }
            //
            imageView.setOnClickListener(this);
            // 将ImageView添加到导航的LinearLayout中
            //ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            linear.addView(imageView);

            HomeVPFragment fragment = new HomeVPFragment();
            Bundle bundle = new Bundle();
            Log.e(TAG, "HomePagerFragment=======" + bannerBeans.get(i).getImg_url());
            bundle.putString("path", bannerBeans.get(i).getImg_url());
            fragment.setArguments(bundle);
            fragments.add(fragment);
        }
        HomePagerVPAdapter adapter = new HomePagerVPAdapter(getActivity().getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
//        handler.sendEmptyMessage(3);
        //加载 精选专题
        for (int i = 0; i < topicBeans.size(); i++) {
            ImageView image = new ImageView(getContext());
            toGetImage(topicBeans.get(i).getImg_url(), image);
            scrollLinear.addView(image);

        }
        //做轮播图
        new Thread() {
            @Override
            public void run() {

                handler.sendEmptyMessage(3);
            }
        };
    }

    private void setListener() {
        viewPager.setOnPageChangeListener(this);
        viewPager.setOffscreenPageLimit(3);
        refreshListView.setOnRefreshListener(this);
        listView.setOnItemClickListener(this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                String s = (String) msg.obj;
                toGetString(s);
                HomePageAdapter adapter = new HomePageAdapter(homeData, getContext());
                listView.setAdapter(adapter);
                break;
            case 2:
                String response = (String) msg.obj;
                toGetHeader(response);
                setData();
                break;
            case 3:
                num = 0;
                viewPager.setCurrentItem(num);
                Log.e(TAG, "00000" + num);
                num++;
                if (num % 5 == 0) {
                    num = 0;
                } else {
                    Message aa = new Message();
                    aa.what = 3;
                    handler.sendMessageDelayed(aa, 2000);
                }
                break;


            case 5:

                String ss = (String) msg.obj;

                break;

        }
        return false;
    }

    //ToDo 下载图片
    private void toGetImage(String s, final ImageView imageViews) {
        OkHttpUtils.get().url(s).tag("iamge").build().execute(new BitmapCallback() {
            @Override
            public void onError(Request request, Exception e) {
                Toast.makeText(getContext(), "下载失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Bitmap response) {
                if (response != null) {
                    imageViews.setImageBitmap(response);
                }

            }
        });
    }


    private void toGetString(String s) {
        //使用Gson解析
        Gson gson = new Gson();
        GetMeiRiuiJian getMeiRiuiJian = gson.fromJson(s, GetMeiRiuiJian.class);
        List<GetMeiRiuiJian.DataBean> data = getMeiRiuiJian.getData();
        Log.e(TAG, "" + data.size());
        homeData = new ArrayList<>();

        for (int i = 0; i < data.size(); i++) {
            HomePageModle page = new HomePageModle();
            page.setId(data.get(i).getId());
            page.setPath(data.get(i).getImg_url());
            page.setItemMerchant(data.get(i).getBusiness());
            page.setItemNumber(data.get(i).getHits());
            page.setItemPrice(data.get(i).getSubtitle());
            page.setItemText(data.get(i).getTitle());
            homeData.add(page);
        }
    }


    private void toGetHeader(String response) {
        Gson gson = new Gson();
        GetListViewHeader getListViewHeader = gson.fromJson(response, GetListViewHeader.class);
        List<GetListViewHeader.DataBean.BannerBean> banner = getListViewHeader.getData().getBanner();
        List<GetListViewHeader.DataBean.ChannelBean> channel = getListViewHeader.getData().getChannel();
//                String search_placeholder = getListViewHeader.getData().getSearch_placeholder();
        List<GetListViewHeader.DataBean.TopicBean> topic = getListViewHeader.getData().getTopic();
        List<GetListViewHeader.DataBean.ZoneBean> zone = getListViewHeader.getData().getZone();

        //初始化数据容器  ViewPager
        bannerBeans = new ArrayList<>();
        for (int i = 0; i < banner.size(); i++) {
            Log.e(TAG, "" + banner.size() + channel.size() + topic.size() + zone.size());
            BannerBean listban = new BannerBean();
//                    banner.get(i)
            listban.setHref(banner.get(i).getHref());
            listban.setImg_url(banner.get(i).getImg_url());
            listban.setSort(banner.get(i).getSort());
            listban.setUrl(banner.get(i).getUrl());
            bannerBeans.add(listban);
        }
        //初始化数据容器  今日优惠
        channelBeans = new ArrayList<>();
        for (int i = 0; i < channel.size(); i++) {
            ChannelBean listcha = new ChannelBean();
            listcha.setHref(channel.get(i).getHref());
            listcha.setImg_url(channel.get(i).getImg_url());
            listcha.setSub_title(channel.get(i).getSub_title());
            listcha.setTitle(channel.get(i).getTitle());
            channelBeans.add(listcha);
        }
        //初始化数据容器  精选专题
        topicBeans = new ArrayList<>();
        for (int i = 0; i < topic.size(); i++) {
            TopicBean listtop = new TopicBean();
            listtop.setImg_url(topic.get(i).getImg_url());
            listtop.setHref(topic.get(i).getHref());
            listtop.setUrl(topic.get(i).getUrl());
            listtop.setSort(topic.get(i).getSort());
            topicBeans.add(listtop);
        }
        //初始化数据容器  篮球
        zoneBeans = new ArrayList<>();
        for (int i = 0; i < zone.size(); i++) {
            ZoneBean listzon = new ZoneBean();
            listzon.setHref(zone.get(i).getHref());
            listzon.setImg_url(zone.get(i).getImg_url());
            listzon.setTitle(zone.get(i).getTitle());
            listzon.setSub_title(zone.get(i).getSub_title());
            zoneBeans.add(listzon);
        }
    }


    @Override
    public void onClick(View v) {
        // 根据v获取在父布局中的索引
        int indexOfChild = linear.indexOfChild(v);
        // 设置ViewPager的显示位置
        viewPager.setCurrentItem(indexOfChild);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        /**
         * ① 将缓存下来的位置 导航点还原状态
         * ② 将选中位置对应的导航点设置为选中状态
         * ③ 缓存选中的位置
         */
        ImageView imageView = (ImageView) linear.getChildAt(cachePosition);
        imageView.setImageResource(R.drawable.falsess);
        ImageView imageViewSelect = (ImageView) linear.getChildAt(position);
        imageViewSelect.setImageResource(R.drawable.truesss);
        cachePosition = position;

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    public void Test(final String string) {
        new Thread() {
            @Override
            public void run() {
                super.run();

                try {
                    URL url = new URL(string);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.connect();
                    OutputStream os = conn.getOutputStream();
                    os.write(("").getBytes());
                    os.close();
                    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        InputStream is = conn.getInputStream();
                        int len;
                        byte[] arr = new byte[1024];
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while ((len = is.read(arr)) != -1) {
                            baos.write(arr, 0, len);
                            baos.flush();
                        }
                        String s = new String(baos.toByteArray());
                        Log.e(TAG, "log++" + s);
                        baos.close();
                        is.close();
                        Message msg = new Message();
                        msg.what = 5;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                }
            }
        }.start();

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        page = 1;
        initData();
        Log.e(TAG,"onPullDownToRefresh"+page);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        page++;
        initData();
        Log.e(TAG, "onPullUpToRefresh" + page);

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


Log.e(TAG,"onItemClick"+position);


    }
}
